<!--
 * @Author: 陈俊升 761723995@qq.com
 * @Date: 2023-12-12 11:14:35
 * @LastEditors: 陈俊升 761723995@qq.com
 * @LastEditTime: 2024-01-03 15:41:10
 * @FilePath: /hr_new_vue3/src/views/Management/Home/LeaveManagement/Certificate/index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!-- 工作台-入职管理-入职手续办理(办理人处理) -->
<template>
  <ContentCard>
    <template #header>
      <PageHeaderNew :title="title" show-back> </PageHeaderNew>
    </template>
    <section>
      <div class="title-box">
        <div class="title">
          <div
            :style="{
              marginLeft: '20px'
            }"
          >
            基础信息
          </div>
        </div>
      </div>
      <a-form ref="HumanForm" :model="humanInfo" autoLabelWidth disabled>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="name" label="姓名" show-colon>
              <a-input v-model="humanInfo.name" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="mobile" label="手机号码" show-colon>
              <a-input v-model="humanInfo.mobile" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="departmentName" label="部门" show-colon>
              <a-input v-model="humanInfo.departmentName" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="positionName" label="职位" show-colon>
              <a-input v-model="humanInfo.positionName" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="superiorName" label="直接上级" show-colon>
              <a-input v-model="humanInfo.superiorName" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="entryTime" label="入职时间" show-colon>
              <a-input v-model="humanInfo.entryTime" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </section>
    <section>
      <div class="title-box">
        <div class="title">
          <div
            :style="{
              marginLeft: '20px'
            }"
          >
            入职手续清单
          </div>
        </div>
      </div>
      <a-table
        :data="formData.data.children"
        :span-method="dataSpanMethod"
        row-key="id"
        :bordered="{
          wrapper: true,
          cell: true,
          headerCell: true,
          bodyCell: true
        }"
        stripe
        :pagination="false"
        :rowSelection="{
          type: 'checkbox',
          showCheckedAll: true
        }"
        v-model:selectedKeys="selectedKeys"
      >
        <template #columns>
          <a-table-column
            align="center"
            title="办理环节"
            dataIndex="handlerProcess"
            :width="200"
          >
          </a-table-column>
          <a-table-column
            :width="200"
            dataIndex="handlerMatters"
            align="center"
            title="办理事项"
          ></a-table-column>
          <a-table-column
            :width="200"
            dataIndex="matterAsk"
            align="center"
            title="办理事项要求"
          ></a-table-column>
          <a-table-column
            :width="200"
            dataIndex="handlerDept"
            align="center"
            title="办理部门"
          >
            <template #cell="{ record }">
              {{ findOrganizationDetail(record.handlerDept as number)?.name }}
            </template>
          </a-table-column>
          <a-table-column
            :width="100"
            dataIndex="handlerUser"
            align="center"
            title="办理人"
          >
            <template #cell="{ record }">
              {{ findHumanDetail(record.handlerUser)?.name }}
            </template>
          </a-table-column>
          <a-table-column
            :width="150"
            dataIndex="userMobile"
            align="center"
            title="办理人联系方式"
          >
            <template #cell="{ record }">
              {{ findHumanDetail(record.handlerUser)?.mobile }}
            </template>
          </a-table-column>
          <a-table-column
            :width="200"
            dataIndex="handlerAddr"
            align="center"
            title="办理地点"
          >
            <template #cell="{ record }">
              {{ findWorkAddressName(record.handlerAddr as number) }}
            </template>
          </a-table-column>
          <a-table-column
            :width="200"
            dataIndex=""
            align="center"
            title="办理状态"
          >
            <template #cell="{ record }">
              <span
                :class="{
                  'text-[#00b42a]':
                    filterStatus(record) === '已完成' ? true : false,
                  'text-[#ccc]':
                    filterStatus(record) === '未完成' ? true : false
                }"
              >
                {{ filterStatus(record) }}
              </span>
            </template>
          </a-table-column>
          <a-table-column
            :width="100"
            dataIndex="createEnter"
            align="center"
            title="员工确认"
          >
            <template #cell="{ record }">
              <!-- <a-button
                type="primary"
                v-if="record.createEnter === 1"
                @click="handleConfirm(record)"
              >
                确认办理</a-button
              > -->
              <span class="text-[#ccc]" v-if="record.createEnter === 1"
                >未确认</span
              >
              <span class="text-blue" v-else>已确认</span>
            </template>
          </a-table-column>
          <a-table-column
            :width="100"
            dataIndex="handlerEnter"
            align="center"
            title="办理人确认"
            fixed="right"
          >
            <template #cell="{ record }">
              <!-- <a-button type="primary" v-if="record.handlerEnter === 0"
                >确认办理</a-button
              > -->
              <!-- <a-button type="primary" v-if="record.handlerEnter === 0"
                >未确认</a-button
              > -->
              <span class="text-[#ccc]" v-if="record.handlerEnter === 1"
                >未确认</span
              >
              <span class="text-blue" v-else>已确认</span>
            </template>
          </a-table-column>
        </template>
      </a-table>
      <footer v-if="type === 1">
        <a-space>
          <a-button class="btn" type="primary" @click="handleConfirm"
            >批量确认</a-button
          >
          <a-button class="btn" @click="handleCancel">批量取消</a-button>
        </a-space>
      </footer>
    </section>
  </ContentCard>
</template>

<script lang="tsx" setup>
import {
  PostEntryProcedure,
  PutEntryProcedure,
  PutEntryProcedureStatus2Human,
  GetEntryProcedureDetail
} from '@/apis/management/human/humanChange/entry/index';
import {
  getOrganizationDetailById,
  getPositionDetailById,
  getHumanDetail,
  getAllWorkAddress,
  getFlatDept,
  getAllHumanRoster
} from '@/utils/common';
import { Modal } from '@arco-design/web-vue';

const route = useRoute();
const title = '入职手续办理(办理人)';
const userId = +route.query.userId; // 待处理人员id
const type = +route.query.type; // 1:处理 2:查看

const formData = reactive({
  data: {}
});

let selectedKeys = ref([]); // 选中的数据
const getTableData = async () => {
  try {
    const res = await GetEntryProcedureDetail({
      // id: 153,
      id: userId,
      type: 2
    });

    // 办理人只能处理自己所对应的事项
    res.children = res.children.map((el: any) => {
      // if (el.handlerUser !== +localStorage.getItem('userId')) {
      //   el.disabled = true;
      // } else el.disabled = false;

      // 暂时写死153用来测试，以后用回上面的注释
      if (el.handlerUser !== 153) {
        el.disabled = true;
      } else el.disabled = false;
      return el;
    });

    formData.data = res;
  } catch (error: unknown) {
    console.log(error);
  }
};
getTableData();

let humanInfo = ref({
  name: '',
  mobile: '',
  departmentName: '',
  positionName: '',
  superiorName: '',
  entryTime: ''
});
let organizationList = ref([]),
  humanList = ref([]),
  workAddress = ref([]);

// 获取部门、办理人等数据
const getHumanData = async () => {
  try {
    const tempHumanInfo = await getHumanDetail(userId);
    const [deptRes, positionRes, superiorRes] = await Promise.all([
      getOrganizationDetailById(tempHumanInfo.departmentId),
      getPositionDetailById(tempHumanInfo.positionId),
      getHumanDetail(tempHumanInfo.superiorId)
    ]);
    humanInfo.value = {
      name: tempHumanInfo.name,
      mobile: tempHumanInfo.mobile,
      departmentName: deptRes?.name,
      positionName: positionRes?.name,
      superiorName: superiorRes?.name,
      entryTime: tempHumanInfo.entryTime
    };
  } catch (error: unknown) {
    console.log(error);
  }
};
getHumanData();

// 获取部门、办理人等数据
const getData = async () => {
  try {
    const [organizationListRes, humanListRes, workAddressRes] =
      await Promise.all([
        getFlatDept(),
        getAllHumanRoster(),
        getAllWorkAddress()
      ]);
    organizationList.value = organizationListRes;
    humanList.value = humanListRes;
    workAddress.value = workAddressRes;
  } catch (error: unknown) {
    console.log(error);
  }
};
getData();
const findOrganizationDetail = (id: number) => {
  return organizationList.value.find((el: any) => el.id === id);
};

const findHumanDetail = (id: number) => {
  return humanList.value.find((el: any) => el.id === id);
};
const findWorkAddressName = (id: number) => {
  return workAddress.value.find((el: any) => el.id === id)?.name;
};

const filterStatus = (record) => {
  if (record.handlerEnter === 2 && record.createEnter === 2) return '已完成';
  return '未完成';
};

// 表格合并
const dataSpanMethod = (datas: any) => {
  const { record, rowIndex, columnIndex, column } = datas;
  // 当检索到相同数据则返回 那条数据
  let arr = formData.data.children.filter((res: any) => {
    return res.handlerProcess == record.handlerProcess;
  });
  // 匹配到相同数据的长度
  // obj.rowspan = arr.length;
  if (
    formData.data.children[rowIndex - 1]?.handlerProcess !=
      record.handlerProcess &&
    (column.dataIndex === 'handlerProcess' ||
      column.dataIndex === 'handlerDept' ||
      column.dataIndex === 'handlerUser' ||
      column.dataIndex === 'handlerAddr' ||
      column.dataIndex === 'userMobile' ||
      column.dataIndex === 'operation' ||
      column.dataIndex === 'personName')
  ) {
    // 匹配到相同数据的长度
    return { rowspan: arr.length };
  }
};

const handleConfirm = async () => {
  try {
    Modal.confirm({
      title: '批量确认',
      content: <>是否确认办理选中的数据?</>,
      onOk: async () => {
        formData.data.children = formData.data.children.map((el: any) => {
          if (selectedKeys.value.includes(el.id)) {
            el.handlerEnter = 2;
          }
          return el;
        });
        await PutEntryProcedure(formData.data);
        selectedKeys.value = [];
      }
    });
  } catch (error: unknown) {
    console.log(error);
  }
};

const handleCancel = async () => {
  try {
    Modal.confirm({
      title: '批量取消',
      content: <>是否取消办理选中的数据?</>,
      onOk: async () => {
        formData.data.children = formData.data.children.map((el: any) => {
          if (selectedKeys.value.includes(el.id)) {
            el.handlerEnter = 1;
          }
          return el;
        });
        await PutEntryProcedure(formData.data);
        selectedKeys.value = [];
      }
    });
  } catch (error: unknown) {
    console.log(error);
  }
};
</script>

<style lang="less" scoped>
:deep(.arco-table-th),
:deep(.arco-table-td) {
  height: 30px;
}

.title-box {
  position: relative;
  .title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 36px;
    border-radius: 4px;
    font-weight: 700;
    margin-bottom: 10px;
    background: #edeffd;
  }
}

.title-box::before {
  position: absolute;
  // top: 33px;
  left: 10px;
  display: inline-block;
  height: 18px;
  top: 50%;
  transform: translateY(-50%);
  width: 5px;
  margin-right: 20px;
  border-radius: 2px;
  // transform: translateY(-50%);
  content: '';
  background-color: #165dff;
}
footer {
  height: 60px;
  width: calc(100% - 100px);
  background-color: #fff;
  box-shadow: 1px -1px 10px 0 #cacaca;
  position: fixed;
  bottom: 0;
  left: 10%;
  display: flex;
  justify-content: center;
  align-items: center;

  .btn {
    width: 120px;
    height: 40px;
    border-radius: 5px;
  }
}
</style>
